
//删除时段
$("#form").on('click', '.delTime_btn', function () {
    $(this).parents("[name='VIPQuantuan']").remove();
})

// page1选择
$("#form").on("change", '[name="discountType"]', function () {
    if ($(this).val() == "0") {
        $(".typeBox1").removeClass("hide")
        $(".typeBox2").addClass("hide")
        // $(this).parents(".form-group").siblings("#timeForm").find("#addPeriod").css("display","none")
    } else {
        $(".typeBox1").addClass("hide")
        $(".typeBox2").removeClass("hide")
    }
})

// page2选择
$("#form").on("change", '[name="timeType"]', function () {
    if ($(this).val() == "1") {
        $("[name=VIPQuantuan]").addClass("hide")
        $('input[name="elecPrice0"]').removeAttr("disabled");
        $('input[name="servicePrice0"]').removeAttr("disabled");
        $(".typeTwoBox").removeClass("hide")
        // $(this).parents(".form-group").siblings("#timeForm").find("#addPeriod").css("display","none")
    } else {
        $("[name=VIPQuantuan]").removeClass("hide")
        $('input[name="elecPrice0"]').attr("disabled", "disabled");
        $('input[name="servicePrice0"]').attr("disabled", "disabled");
        $(".typeTwoBox").addClass("hide")
        // $(this).parents("#timeForm").find("#addPeriod").css("display","inline-block");
    }
})
$("#form").on("change", '[name="D_timeType"]', function () {
    if ($(this).val() == "1") {
        $("[name=VIPQuantuan]").addClass("hide")
        $('input[name="elecPrice0"]').removeAttr("disabled");
        $('input[name="servicePrice0"]').removeAttr("disabled");
        $(".typeOneBox").removeClass("hide")
        // $(this).parents(".form-group").siblings("#timeForm").find("#addPeriod").css("display","none")
    } else {
        $("[name=VIPQuantuan]").removeClass("hide")
        $('input[name="elecPrice0"]').attr("disabled", "disabled");
        $('input[name="servicePrice0"]').attr("disabled", "disabled");
        $(".typeOneBox").addClass("hide")
        // $(this).parents("#timeForm").find("#addPeriod").css("display","inline-block");
    }
})
// page3选择
$("#form").on("change", '[name="memberType"]', function () {
    if ($(this).val() == "0") {
        $("#inputBox").addClass("hide")
    } else {
        $("#inputBox").removeClass("hide")
    }
})


//添加时段
var timeStr = '';
$("#form").delegate('.addPeriod', 'click', function () {
    if ($("input[name='discountType']:checked").val() == "1") {
        var flag = true
        $(".typeBox2 [name='VIPQuantuan']").each(function () {
            var startPeriod =  $(this).find("[name='startPeriod']").val()
            var endPeriod =  $(this).find("[name='endPeriod']").val()
            var elecPrice =  $(this).find("[name='elecPrice']").val()
            var servicePrice =  $(this).find("[name='servicePrice']").val()
            if (startPeriod=="" || endPeriod=="" || elecPrice=="" || servicePrice=="") {
                layer.msg('请先填写数据');
                flag = false
                return false
            }
        })
        if(!flag){
            return
        }
        // return flag;
        // var startPeriod = $(this).parents("#form").find("input[name='startPeriod']").val()
        // var endPeriod = $(this).parents("#form").find("input[name='endPeriod']").val()
        // var elecPrice = $(this).parents("#form").find("input[name='elecPrice']").val()
        // var servicePrice = $(this).parents("#form").find("input[name='servicePrice']").val()

        if ($(".typeBox2 [name='VIPQuantuan']").length > 7) {
            layer.msg('时间段不能超过8个')
            return
        }
        var count = $(".typeBox2 [name='VIPQuantuan']").length + 1;

        timeStr = ` <div class="mt10 QuantuanBox" name="VIPQuantuan">
               <label class="ml10" style="margin-left: 30px">时段${count}:</label>
               <input id="startPeriod${count}" autocomplete="off" required name="startPeriod" type="text" class="form-control ml10 inlineBlock width10" value="00:00:00" placeholder="开始时间">
               <span class="mlr">--</span>
               <input id="endPeriod${count}" autocomplete="off" required name="endPeriod" type="text" class="form-control inlineBlock width10" value="00:59:59" placeholder="结束时间">
               <span class="ml10">电费优惠价*</span>
               <input id="elecPrice${count}" name="elecPrice" required autocomplete="off" type="text" class="form-control inlineBlock width8" placeholder="">
               <span class="ml10">服务费优惠价*</span>
               <input id="servicePrice${count}" name="servicePrice" required autocomplete="off" type="text" class="form-control inlineBlock width8" placeholder="">
               <a class="btn btn-danger btn-sm delTime_btn"   style="margin-left: 30px;margin-top: 3px" >删除时段</a>
               </div>`
        $(".typeBox2 [name='VIPQuantuan']:last").after(timeStr);
        // $("#startPeriod"+count).jeDate(startPeriod);
        // $("#endPeriod"+count).jeDate(endPeriod);
        layui.use('laydate', function () {
            var laydate = layui.laydate;

            //执行一个laydate实例
            var endDate = laydate.render({
                elem: '#endPeriod' + count, //指定元素
                type: 'time',
                format: 'HH:mm:ss',
                trigger: 'click',
                position:'fixed',
                change: function (value, date) {

                    console.log(date)
                    startDate.config.max = {
                        year: date.year,
                        month: date.month - 1,//关键
                        date: date.date,
                        hours: date.hours,
                        minutes: date.minutes,
                        seconds: date.seconds
                    }
                }
            });
            var startDate = laydate.render({
                elem: '#startPeriod' + count,
                type: 'time',
                format: 'HH:mm:ss',
                trigger: 'click',
                position:'fixed',
                change: function (value, date) {
                    endDate.config.min = {
                        year: date.year,
                        month: date.month - 1, //关键
                        date: date.date,
                        hours: date.hours,
                        minutes: date.minutes,
                        seconds: date.seconds
                    };
                }
            });

        })
    } else {
        var startPeriod = $(this).parents("#form").find("input[name='startPeriods']").val()
        var endPeriod = $(this).parents("#form").find("input[name='endPeriods']").val();
        var elecPrice = '';
        var servicePrice = '';
        var discount = $(this).parents("#form").find("input[name='discounts']").val()
        if (!startPeriod && !endPeriod && !discount) {
            layer.msg('请先填写数据')
            return
        }
        var flag = true
        $(".typeBox1 [name='VIPQuantuan']").each(function () {
            var startPeriod =  $(this).find("[name='startPeriods']").val()
            var endPeriod =  $(this).find("[name='endPeriods']").val()
            var discount = $(this).find("input[name='discounts']").val()
            if (startPeriod=="" || endPeriod=="" || discount=="") {
                layer.msg('请先填写数据');
                flag = false
                return false
            }
        })
        if(!flag){
            return
        }

        if ($(".typeBox1 [name='VIPQuantuan']").length > 7) {
            layer.msg('时间段不能超过8个')
            return
        }
        var count = $(".typeBox1 [name='VIPQuantuan']").length + 1;

        timeStr = ` <div class="mt10 QuantuanBox" name="VIPQuantuan">
               <label class="ml10" style="margin-left: 30px">时段${count}:</label>
               <input id="D_startPeriod${count}" autocomplete="off" required name="startPeriods" type="text" class="form-control ml10 inlineBlock width10" value="00:00:00" placeholder="开始时间">
               <span class="mlr">--</span>
               <input id="D_endPeriod${count}" autocomplete="off" required name="endPeriods" type="text" class="form-control inlineBlock width10" value="00:59:59" placeholder="结束时间">
               <span class="ml10">服务费折扣*</span>
               <input id="D_discounts${count}" name="discounts" required autocomplete="off" type="text" class="form-control inlineBlock width8" placeholder="">
               <a class="btn btn-danger btn-sm delTime_btn"   style="margin-left: 30px;margin-top: 3px" >删除时段</a>
               </div>`
        $(".typeBox1 [name='VIPQuantuan']:last").after(timeStr);
        // $("#startPeriod"+count).jeDate(startPeriod);
        // $("#endPeriod"+count).jeDate(endPeriod);
        layui.use('laydate', function () {
            var laydate = layui.laydate;

            //执行一个laydate实例
            var endDate = laydate.render({
                elem: '#D_endPeriod' + count, //指定元素
                type: 'time',
                format: 'HH:mm:ss',
                trigger: 'click',
                position:'fixed',
                change: function (value, date) {

                    console.log(date)
                    startDate.config.max = {
                        year: date.year,
                        month: date.month - 1,//关键
                        date: date.date,
                        hours: date.hours,
                        minutes: date.minutes,
                        seconds: date.seconds
                    }
                }
            });
            var startDate = laydate.render({
                elem: '#D_startPeriod' + count,
                type: 'time',
                format: 'HH:mm:ss',
                trigger: 'click',
                position:'fixed',
                change: function (value, date) {
                    endDate.config.min = {
                        year: date.year,
                        month: date.month - 1, //关键
                        date: date.date,
                        hours: date.hours,
                        minutes: date.minutes,
                        seconds: date.seconds
                    };
                }
            });

        })
    }

})


layui.use('laydate', function () {
    var laydate = layui.laydate;

    //执行一个laydate实例
    var endDate = laydate.render({
        elem: '#D_endPeriod1', //指定元素
        type: 'time',
        format: 'HH:mm:ss',
        trigger: 'click',
        position:'fixed',
        change: function (value, date) {

            console.log(date)
            startDate.config.max = {
                year: date.year,
                month: date.month - 1,//关键
                date: date.date,
                hours: date.hours,
                minutes: date.minutes,
                seconds: date.seconds
            }
        }
    });
    var startDate = laydate.render({
        elem: '#D_startPeriod1',
        type: 'time',
        format: 'HH:mm:ss',
        trigger: 'click',
        position:'fixed',
        change: function (value, date) {
            endDate.config.min = {
                year: date.year,
                month: date.month - 1, //关键
                date: date.date,
                hours: date.hours,
                minutes: date.minutes,
                seconds: date.seconds
            };
        }
    });

})

layui.use('laydate', function () {
    var laydate = layui.laydate;

    //执行一个laydate实例
    var endDate = laydate.render({
        elem: '#endPeriod1', //指定元素
        type: 'time',
        format: 'HH:mm:ss',
        trigger: 'click',
        position:'fixed',
        change: function (value, date) {

            console.log(date)
            startDate.config.max = {
                year: date.year,
                month: date.month - 1,//关键
                date: date.date,
                hours: date.hours,
                minutes: date.minutes,
                seconds: date.seconds
            }
        }
    });
    var startDate = laydate.render({
        elem: '#startPeriod1',
        type: 'time',
        format: 'HH:mm:ss',
        trigger: 'click',
        position:'fixed',
        change: function (value, date) {
            endDate.config.min = {
                year: date.year,
                month: date.month - 1, //关键
                date: date.date,
                hours: date.hours,
                minutes: date.minutes,
                seconds: date.seconds
            };
        }
    });

})


layui.use('laydate', function () {
    var laydate = layui.laydate;
    var myDate = new Date();
    var beginTime = laydate.render({
        elem: '#beginTime',
        type: 'datetime',
        format: 'yyyy-MM-dd HH:mm:ss',
        min:-10000,
        trigger: 'click',
        position:'fixed',
        done:function(value,date){
//    		console.log(value); //得到日期生成的值，如：2017-08-18
//    	    console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
            endTime.config.min={
                year:date.year,
                month:date.month-1,//关键
                date:date.date,
                hours:date.hours,
                minutes:date.minutes,
                seconds:date.seconds
            };

        }
    });
    var endTime = laydate.render({
        elem: '#endTime',
        type: 'datetime',
        format: 'yyyy-MM-dd HH:mm:ss',
        trigger: 'click',
        position:'fixed',
        done:function(value,date){
//    		console.log(value); //得到日期生成的值，如：2017-08-18
//    	    console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
            beginTime.config.max={
                year:date.year,
                month:date.month-1,//关键
                date:date.date,
                hours:date.hours,
                minutes:date.minutes,
                seconds:date.seconds
            }

        }
    });

});


$(document).ready(function () {
    $("#form").steps({
        bodyTag: "fieldset",
        labels: {
            finish: "完成", // 修改按钮得文本
            next: "下一步", // 下一步按钮的文本
            previous: "上一步", // 上一步按钮的文本
            loading: "Loading ..."
        },
        onStepChanging: function (event, currentIndex, newIndex) {
            var valid = true
            // console.log(111)
            // alert("当前"+currentIndex)
            // alert("下页"+newIndex)
            // Always allow going backward even if the current step contains invalid fields!
            if (currentIndex > newIndex) {
                return true;
            }

            // Forbid suppressing "Warning" step if the user is to young
            if (newIndex === 3 && Number($("#age").val()) < 18) {
                return false;
            }

            var form = $(this);

            // Clean up if user went backward before
            if (currentIndex < newIndex) {
                // To remove error styles
                $(".body:eq(" + newIndex + ") label.error", form).remove();
                $(".body:eq(" + newIndex + ") .error", form).removeClass("error");
            }

            // Disable validation on fields that are disabled or hidden.
            form.validate().settings.ignore = ":disabled,:hidden";
            if (form.valid() && currentIndex == 0) {
                var formData = new FormData();
                formData.append("elecStationId", $("#elecStationId").val()),
                    formData.append("policyName", $("[name='policyName']").val()),
                    formData.append("discountType", $("input[name='discountType']:checked").val()),
                    formData.append("discountPolicyId", $("#discountPolicyId").val()),
                    // formData.append("policyDesc", $("[name='policyDesc']").val()),
                    // formData.append("discount", $("#discount").val()),
                    formData.append("beginTime", $("#beginTime").val()),
                    formData.append("endTime", $("#endTime").val()),
                    console.warn(formData);
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: prefix + "/saveOrUpdateDiscountPolicy",
                    //data: $('#addChargeBanner').serialize(),
                    data: formData,
                    processData: false,
                    contentType: false,
                    async: false,
                    error: function (request) {
                        parent.layer.alert("Connection error");
                    },
                    success: function (data) {
                        if (data.status == 200) {
                            $("#discountPolicyId").val(data.data.discountPolicyId);
                            valid = form.valid();
                        } else {
                            parent.layer.msg(data.message);
                            valid = false;
                        }

                    }
                });
            } else if (form.valid() && currentIndex == 1) {
                var flag = true
                // 折扣且全天
                var totalData = {};
                if ($(".typeBox1 input[name='D_timeType']:checked").val() == "1" && $(" input[name='discountType']:checked").val() == "0") {
                    totalData.elecStationId = $("#elecStationId").val();
                    totalData.discountPolicyId = $("#discountPolicyId").val();
                    totalData.discountType= $("input[name='discountType']:checked").val()
                    totalData.discount = $("#D_discount0").val();
                    totalData.timeType = $("input[name='D_timeType']:checked").val()
                    // 折扣且时段
                } else if ($(".typeBox1 input[name='D_timeType']:checked").val() == "2" && $("input[name='discountType']:checked").val() == "0") {
                    var dataTimeArr = $(".typeBox1 [name='VIPQuantuan']").map(function (index) {
                        var object = {};
                        if ($('#D_startPeriod' + (index + 1)).val() || $('#D_endPeriod' + (index + 1)).val()) {
                            object.startPeriod = ($('#D_startPeriod' + (index + 1)).val());
                            object.endPeriod = ($('#D_endPeriod' + (index + 1)).val());
                            object.discount = $('#D_discounts' + (index + 1)).val();
                            return object
                        } else {
                            object.startPeriod = "";
                            object.endPeriod = "";
                            object.discount = "";
                            return object
                        }

                    }).get()
                    totalData.discountTimeSaveVoList = JSON.stringify(dataTimeArr)
                    totalData.discountType= $("input[name='discountType']:checked").val()
                    totalData.elecStationId = $("#elecStationId").val();
                    totalData.discountPolicyId = $("#discountPolicyId").val();
                    totalData.timeType = $("input[name='D_timeType']:checked").val()

                    $(".typeBox1 [name='VIPQuantuan']").each(function () {
                        var startPeriod =  $(this).find("[name='startPeriods']").val()
                        var endPeriod =  $(this).find("[name='endPeriods']").val()
                        var discount = $(this).find("input[name='discounts']").val()
                        if (startPeriod=="" || endPeriod=="" || discount=="") {
                            layer.msg('数据不能为空');
                            flag = false
                            return false
                        }
                        if(discount<0 || discount>1){
                            layer.msg('请输入有效折扣范围');
                            flag = false
                        }
                    })


                } else if ($(".typeBox2 input[name='timeType']:checked").val() == "1" && $("input[name='discountType']:checked").val() == "1") {
                    totalData.elecPrice = $("input[name='elecPrice0']").val()
                    totalData.servicePrice = $("input[name='servicePrice0']").val()
                    totalData.elecStationId = $("#elecStationId").val();
                    totalData.discountPolicyId = $("#discountPolicyId").val();
                    totalData.discountType= $("input[name='discountType']:checked").val()
                    totalData.timeType = $("input[name='timeType']:checked").val()
                } else if ($(".typeBox2 input[name='timeType']:checked").val() == "2" && $("input[name='discountType']:checked").val() == "1") {
                    var dataTimeArr = $(".typeBox2 [name='VIPQuantuan']").map(function (index) {
                        var object = {};
                        if ($('#startPeriod' + (index + 1)).val() || $('#endPeriod' + (index + 1)).val()) {
                            object.startPeriod = ($('#startPeriod' + (index + 1)).val());
                            object.endPeriod = ($('#endPeriod' + (index + 1)).val());
                            object.elecPrice = $('#elecPrice' + (index + 1)).val();
                            object.servicePrice = $('#servicePrice' + (index + 1)).val();
                            return object
                        } else {
                            object.startPeriod = "";
                            object.endPeriod = "";
                            object.elecPrice = "";
                            object.servicePrice = "";
                            return object
                        }
                    }).get()
                    totalData.discountTimeSaveVoList = JSON.stringify(dataTimeArr)
                    totalData.elecStationId = $("#elecStationId").val();
                    totalData.discountType= $("input[name='discountType']:checked").val()
                    totalData.discountPolicyId = $("#discountPolicyId").val();
                    totalData.timeType = $("input[name='timeType']:checked").val()

                    $(".typeBox2 [name='VIPQuantuan']").each(function () {
                        var startPeriod =  $(this).find("[name='startPeriod']").val()
                        var endPeriod =  $(this).find("[name='endPeriod']").val()
                        var elecPrice =  $(this).find("[name='elecPrice']").val()
                        var servicePrice =  $(this).find("[name='servicePrice']").val()
                        if (startPeriod=="" || endPeriod=="" || elecPrice=="" || servicePrice=="") {
                            layer.msg('数据不能为空');
                            flag = false
                            return false
                        }
                        if(elecPrice<0 || servicePrice<0){
                            layer.msg('请输入价格折扣范围');
                            flag = false
                        }
                    })
                }
                if(!flag){
                    return
                }
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: prefix + "/saveOrUpdateDiscountTime",
                    //data: $('#addChargeBanner').serialize(),
                    data: JSON.stringify(totalData),
                    processData: false,
                    contentType: false,
                    async: false,
                    error: function (request) {
                        parent.layer.alert("Connection error");
                    },
                    success: function (data) {
                        if (data.status == 200) {
                            // console.log(data.data.discountPolicyId)
                            console.log(data)
                            $("#discountPolicyId").val(data.data.discountPolicyId);
                            valid = form.valid();
                        } else {
                            parent.layer.msg(data.message);
                            valid = false;
                        }

                    }
                });
            } else {
                return form.valid();
            }


            return valid

            // alert(form.valid())
            // return form.valid();

            // Start validation; Prevent going forward if false


        },
        onStepChanged: function (event, currentIndex, priorIndex) {

            // Suppress (skip) "Warning" step if the user is old enough.
            if (currentIndex === 2 && Number($("#age").val()) >= 18) {
                $(this).steps("下一个");
            }

            // Suppress (skip) "Warning" step if the user is old enough and wants to the previous step.
            if (currentIndex === 2 && priorIndex === 3) {
                $(this).steps("上一个");

            }
        },
        onFinishing: function (event, currentIndex) {
            var loading;
            var valid = true
            var form = $(this);
            // if(!form.valid()){
            //     return
            // }
            var totalData = {}
            if ($("input[name='memberType']:checked").val() == "0") {
                // alert($("#discountPolicyId").val())
                console.log($("#discountPolicyId").val())
                totalData.discountPolicyId = $("#discountPolicyId").val()
                totalData.memberType = $("input[name='memberType']:checked").val()
                totalData = JSON.stringify(totalData);
            }else{
                totalData.discountPolicyId = $("#discountPolicyId").val()
                totalData.memberType = $("input[name='memberType']:checked").val()
                totalData.list = $("#mobileArea").val()
                totalData = JSON.stringify(totalData);
                if($("#mobileArea").val()==""){
                    parent.layer.msg("请填写用户手机号");
                    return
                }
            }

            $.ajax({
                cache: false,
                type: "POST",
                url: prefix + "/saveOrUpdateDiscountMember",
                //data: $('#addChargeBanner').serialize(),
                data: totalData,
                processData: false,
                contentType: false,
                async:true ,
                beforeSend:function(){
                    // alert("保存中。。")
                    // parent.layer.msg("baocunzhong");
                    loading = layer.load(0, {
                        shade: false,
                        time: 1000
                    });
                },
                error: function (request) {
                    layer.close(loading);
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    layer.close(loading);
                    if (data.status == 200) {
                        valid = form.valid()
                        if(data.message!=null){
                            parent.layer.msg(data.message);
                            history.back()
                        }

                    }else if(data.status == 500){
                        parent.layer.msg(data.message);
                        valid = false;
                    }
                    else {
                        parent.layer.msg(data.message);
                        valid = false;
                    }

                }
            });



            // Disable validation on fields that are disabled.
            // At this point it's recommended to do an overall check (mean ignoring only disabled fields)
            form.validate().settings.ignore = ":disabled";

            // Start validation; Prevent form submission if false
            return valid;
        },
        onFinished: function (event, currentIndex) {
            var form = $(this);

            // Submit form input
            // form.submit();
        }
    }).validate({
        errorPlacement: function (error, element) {
            element.after(error);
        },
        rules: {
            policyName: {
                required: true,
            },
            discountType: {
                required: true
            },
            discount: {
                required: true
            },
            beginTime: {
                required: true
            },
            endTime: {
                required: true
            },
            discount0:{
                required: true,
                // number:true,
                min:0,
                max:1
            },
            discounts:{
                required: true,
                // number:true,
                min:0,
                max:1
            },
            startPeriod:{
                required: true,
            },
            endPeriod:{
                required: true,
            }
            ,
            startPeriods:{
                required: true,
            },
            endPeriods:{
                required: true,
            },
            elecPrice:{
                required: true,
            },
            servicePrice:{
                required: true,
            }

        }, messages: {
            policyName: {
                required: "",
            },
            discountType: {
                required: ""
            },
            discount: {
                required: ""
            },
            beginTime: {
                required: ""
            },
            endTime: {
                required: ""
            },
            discount0:{
                required: ""
            },
            discounts:{
                required: ""
            },
            startPeriod:{
                required: "",
            },
            endPeriod:{
                required: "",
            },
            startPeriods:{
                required: "",
            },
            endPeriods:{
                required: "",
            },
            elecPrice:{
                required: "",
            },
            servicePrice:{
                required: "",
            }
        },
    });
});




addDiscountPolicy.init();
